#include "udp_receiver.hpp"
#include <Arduino.h>
#include "display.hpp"   // 用于 showVoiceData()
#include <WiFi.h>
WiFiUDP udp;

void initUDP(uint16_t port) {
  udp.begin(port);
  Serial.print("UDP listening on ");
  Serial.println(WiFi.localIP());
}

void updateUDP() {
  int len = udp.parsePacket();
  if (len > 0) {
    static char buf[128];
    int n = udp.read(buf, sizeof(buf) - 1);
    buf[n] = '\0';
    String data(buf);
    Serial.println("RX: " + data);

    static String classLabel = "";
    static String temperature = "";
    static String picture = "";

    int classIndex = data.indexOf("\"class\":\"");
    if (classIndex != -1) {
      int start = classIndex + 9;
      int end = data.indexOf("\"", start);
      if (end != -1) classLabel = data.substring(start, end);
    }

    int tempIndex = data.indexOf("\"Temp\":\"");
    if (tempIndex != -1) {
      int start = tempIndex + 8;
      int end = data.indexOf("\"", start);
      if (end != -1) temperature = data.substring(start, end);
    }

    int picIndex = data.indexOf("\"Picture\":\"");
    if (picIndex != -1) {
      int start = picIndex + 11;
      int end = data.indexOf("\"", start);
      if (end != -1) picture = data.substring(start, end);
    }

    showData(classLabel, temperature, picture);
  }
}
